#include <iostream>
#include <memory>
#include <arpa/inet.h>
#include "TCPServer.hpp"

// ./client 127.0.0.1 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "指令错误" << std::endl;
        return 0;
    }
    std::string ip = argv[1];
    int port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "tcp socket create fail" << std::endl;
        exit(1);
    }
    std::cout << "tcp socket create success" << std::endl;

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    // inet_pton(AF_INET, ip.c_str(), &addr.sin_addr);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len = sizeof(addr);
    int n = connect(sockfd, (struct sockaddr *)&addr, len);
    if (n < 0)
    {
        std::cout << "connect socket fail" << std::endl;
        exit(1);
    }

    while (true)
    {
        std::cout << "Enter #";
        std::string request;
        std::getline(std::cin, request);
        std::cout << request << std::endl;

        send(sockfd, request.c_str(), request.size(), 0);

        char buffer[1024];
        int m = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        buffer[m] = 0;

        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
        else if (m == 0)
        {
            std::cout << "read end" << std::endl;
            exit(1);
        }
        else 
        {
            std::cout << "read fail" << std::endl;
            exit(1);
        }
    }
    return 0;
}